package com.heima.scan.message;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.heima.common.contants.MessageConstants;
import com.heima.scan.service.NewsScanService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class NewsScanMessageListener {
    @Autowired
    private NewsScanService newsScanService;

    /**
     * 交换机：GREEN_SCAN_EXCHANGE = "scan.exchange";
     * 队列：NEWS_SCAN_QUEUE = "scan.news.queue";
     * key：news
     * @param message
     */
    // 监听新闻扫描队列的消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MessageConstants.NEWS_SCAN_QUEUE,durable = "true"),
            exchange = @Exchange(value = MessageConstants.GREEN_SCAN_EXCHANGE,type = ExchangeTypes.DIRECT),
            key = MessageConstants.NEWS_SCAN_KEY
    ))
    public void listenerNewsScanMessage(String message) throws Exception {
        // 如果消息为空，则直接返回
        if (StrUtil.isEmpty(message)){
            return;
        }
        // 解析消息为JSON对象
        JSONObject jsonObject = JSONUtil.parseObj(message);
        // 获取新闻ID
        Long newsId = jsonObject.getLong("newsId");
        // 获取新闻文本内容
        String text = jsonObject.getStr("text");
        // 获取新闻图片列表
        List<String> list = jsonObject.getJSONArray("images").toList(String.class);
        // 调用审核业务层，对文章文本和图片进行审核
        newsScanService.scan(newsId, text,list);
    }
}
